const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);

// 配置Socket.IO
const io = new Server(server, {
	cors: {
		origin: '*', // 允许所有来源
		methods: ['GET', 'POST'],
	},
});

// 存储在线用户
const users = new Map();

// 事件处理
io.on('connection', socket => {
	console.log(`新连接: ${socket.id}`);

	// 用户加入
	socket.on('join', username => {
		users.set(socket.id, username);
		socket.broadcast.emit('message', {
			type: 'system',
			content: `${username} 加入了聊天室`,
		});
		// 发送当前在线用户列表
		io.emit('users', Array.from(users.values()));
	});

	// 消息处理
	socket.on('message', msg => {
		const username = users.get(socket.id);
		io.emit('message', {
			type: 'user',
			username: username,
			content: msg,
			time: new Date().toLocaleTimeString(),
		});
	});

	// 用户离开
	socket.on('disconnect', () => {
		const username = users.get(socket.id);
		if (username) {
			users.delete(socket.id);
			io.emit('message', {
				type: 'system',
				content: `${username} 离开了聊天室`,
			});
			io.emit('users', Array.from(users.values()));
		}
	});
});

// 静态文件服务
app.use(express.static('public'));

// 启动服务器
const PORT = 3000;
server.listen(PORT, () => {
	console.log(`服务运行在 http://localhost:${PORT}`);
});
